package com.sendpo.zjx.sendpo.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.SearchHistory;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.wefika.flowlayout.FlowLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.ex.DbException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/17.
 */

public class SearchContentActivity extends AppCompatActivity {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.right_head)
    ImageView rightHead;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.topseardch_flowlayout)
    FlowLayout topseardchFlowlayout;
    @BindView(R.id.history_flowlayout)
    FlowLayout history_flowlayout;

  @BindView(value = R.id.swiperefresh)
  public SwipeRefreshLayout swiperefresh;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchcontent);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    private void initComponent() {
        swiperefresh.setColorSchemeColors(getResources().getColor(R.color.default_theme));
        swiperefresh.setProgressViewOffset(false, 0, DensityUtil.dip2px(150));
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                query();
                queryhistory();
            }
        });
        query();
        queryhistory();
    }

    @OnClick(value = {R.id.backbt, R.id.right_head})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.right_head:
                if (TextUtils.isEmpty(searchEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "请输入内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (searchEdit.getText().toString().trim().length()<2) {
                    Toast.makeText(getApplicationContext(), "搜索内容不能小于两个字", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("data", searchEdit.getText().toString().trim());
                Tools.redirectActivity(this, StoreSearchActivity.class, map);
                webaddHistory(searchEdit.getText().toString().trim());
                break;
        }
    }

    public void query(){
        swiperefresh.setRefreshing(true);
        String cache_result= Tools.getCache(this, HttpUrl.searchmerchandiseabove10query);
        Gson gson=new Gson();
        if(cache_result!=null&&!cache_result.equals("")){

            try {
                JSONObject jsonObject=new JSONObject(cache_result);
                switch (jsonObject.getInt("state")){
                    case HttpCode.SUCCESS:
                        JSONArray ja=jsonObject.getJSONArray("data");
                        if(ja!=null&&ja.length()!=0){
                            topseardchFlowlayout.removeAllViews();
                            for(int i=0;i<ja.length();i++){
                                final String d=ja.getString(i);
                                TextView button=new TextView(SearchContentActivity.this);
                                FlowLayout.LayoutParams lp=new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT,
                                        FlowLayout.LayoutParams.WRAP_CONTENT);
                                lp.setMargins(DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10));
                                button.setLayoutParams(lp);
                                button.setPadding(DensityUtil.dip2px(20),
                                        DensityUtil.dip2px(10),
                                        DensityUtil.dip2px(20),
                                        DensityUtil.dip2px(10));
                                button.setBackgroundResource(R.drawable.default_whiltegray_40dp);
                                button.setText(""+d);
                                button.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        searchEdit.setText(""+d);
                                        rightHead.performClick();
                                    }
                                });
                                topseardchFlowlayout.addView(button);
                            }
                        }
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        Xutils.POST(HttpUrl.searchmerchandiseabove10query, null, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                swiperefresh.setRefreshing(false);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                switch (jsonObject.getInt("state")){
                    case HttpCode.SUCCESS:
                           JSONArray ja=jsonObject.getJSONArray("data");
                                if(ja!=null&&ja.length()!=0){
                                    Tools.setCache(SearchContentActivity.this, HttpUrl.searchmerchandiseabove10query,result);
                                    topseardchFlowlayout.removeAllViews();
                                     for(int i=0;i<ja.length();i++){
                                          final String d=ja.getString(i);
                                         TextView button=new TextView(SearchContentActivity.this);
                                         FlowLayout.LayoutParams lp=new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT,
                                                 FlowLayout.LayoutParams.WRAP_CONTENT);
                                         lp.setMargins(DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10));
                                         button.setLayoutParams(lp);
                                         button.setPadding(DensityUtil.dip2px(20),
                                                 DensityUtil.dip2px(10),
                                                 DensityUtil.dip2px(20),
                                                 DensityUtil.dip2px(10));
                                         button.setBackgroundResource(R.drawable.default_whiltegray_40dp);
                                         button.setText(""+d);
                                         button.setOnClickListener(new View.OnClickListener() {
                                             @Override
                                             public void onClick(View view) {
                                                 searchEdit.setText(""+d);
                                                 rightHead.performClick();
                                             }
                                         });
                                         topseardchFlowlayout.addView(button);
                                     }
                                }
                        break;
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swiperefresh.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void queryhistory(){
        DbManager db= Tools.getDbManager(this.getApplication(), Tools.DBNAME, Tools.DBVERSION);
        try {
            List<SearchHistory> sh= db.selector(SearchHistory.class).orderBy("Id",true).findAll();
                   if(sh!=null&&sh.size()!=0){
                       history_flowlayout.removeAllViews();
                       for(int i=0;i<sh.size();i++){
                           final String d=sh.get(i).getContent();
                           TextView button=new TextView(SearchContentActivity.this);
                           FlowLayout.LayoutParams lp=new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT,
                                   FlowLayout.LayoutParams.WRAP_CONTENT);
                           lp.setMargins(DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10),DensityUtil.dip2px(10));
                           button.setLayoutParams(lp);
                           button.setPadding(DensityUtil.dip2px(20),
                                   DensityUtil.dip2px(10),
                                   DensityUtil.dip2px(20),
                                   DensityUtil.dip2px(10));
                           button.setBackgroundResource(R.drawable.default_whiltegray_40dp);
                           button.setText(""+d);
                           button.setOnClickListener(new View.OnClickListener() {
                               @Override
                               public void onClick(View view) {
                                   searchEdit.setText(""+d);
                                   rightHead.performClick();
                               }
                           });
                           history_flowlayout.addView(button);
                       }
                   }
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

   public void webaddHistory(String content){
        Map<String,String> map=new HashMap<>();
         map.put("searchContent",""+content);
       Xutils.POST(HttpUrl.searchmerchandiseaddhistory, map, new Callback.CommonCallback<String>() {
           @Override
           public void onSuccess(String result) {
               try {
                   JSONObject jsonObject=new JSONObject(result);
                   switch (jsonObject.getInt("state")){
                       case HttpCode.SUCCESS:
                           break;
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }

           @Override
           public void onError(Throwable ex, boolean isOnCallback) {

           }

           @Override
           public void onCancelled(CancelledException cex) {

           }

           @Override
           public void onFinished() {

           }
       });
   }

}
